<?php
/*
 * @Author: fk 1031041088@qq.com
 * @Date: 2024-12-11 21:30:55
 * @LastEditors: fk 1031041088@qq.com
 * @LastEditTime: 2024-12-11 21:48:51
 */
require_once '../config/oss_config.php';
require_once '../config/database.php';

// 引入OSS命名空间
use OSS\OssClient;
use OSS\Core\OssException;

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => '无效的请求方法']);
    exit;
}

try {
    $file = $_FILES['image'];
    
    // 初始化OSS客户端
    $ossClient = new OssClient(
        OSS_ACCESS_KEY_ID,
        OSS_ACCESS_KEY_SECRET,
        OSS_ENDPOINT
    );
    
    // 生成唯一文件名
    $filename = uniqid() . '_' . $file['name'];
    $object = 'images/' . $filename;
    
    // 上传到OSS
    $result = $ossClient->uploadFile(OSS_BUCKET, $object, $file['tmp_name']);
    
    // 保存到数据库
    $url = $result['info']['url'];
    $stmt = $pdo->prepare("INSERT INTO images (filename, oss_path, url) VALUES (?, ?, ?)");
    $stmt->execute([$filename, $object, $url]);
    
    // 返回图片信息
    echo json_encode([
        'success' => true,
        'url' => $url,
        'id' => $pdo->lastInsertId()
    ]);
    
} catch (OssException $e) {
    echo json_encode(['error' => '上传到OSS失败：' . $e->getMessage()]);
} catch (PDOException $e) {
    echo json_encode(['error' => '数据库操作失败：' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['error' => '系统错误：' . $e->getMessage()]);
}
?> 